package org.jeecg.modules.util;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;

public class ByteConvert {

    public static int bytesToInt_LE(byte[] bytes) {
        int result = 0;
        if (bytes == null || bytes.length < 0)
            return -1;
        ByteBuffer buffer = ByteBuffer.wrap(bytes);
        buffer.order(ByteOrder.LITTLE_ENDIAN);
        if (bytes.length == 4) {
            result = buffer.getInt();
        } else if (bytes.length == 2) {
            // 端口号：0 ~ 65535; Short: -32768 ~ 32767
            result = buffer.getShort();
        }
        return result;
    }

    public static float bytesToFloat_LE(byte[] bytes) {
        if (bytes == null || bytes.length < 0)
            return -1;
        ByteBuffer buffer = ByteBuffer.wrap(bytes);
        buffer.order(ByteOrder.LITTLE_ENDIAN);
        return buffer.getFloat();
    }

    public static long bytesToLong_LE(byte[] bytes) {
        if (bytes == null || bytes.length < 0)
            return -1;
        ByteBuffer buffer = ByteBuffer.wrap(bytes);
        buffer.order(ByteOrder.LITTLE_ENDIAN);
        return buffer.getLong();
    }

    public static double bytesToDouble_LE(byte[] bytes) {
        if (bytes == null || bytes.length < 0)
            return -1;
        ByteBuffer buffer = ByteBuffer.wrap(bytes);
        buffer.order(ByteOrder.LITTLE_ENDIAN);
        return buffer.getDouble();
    }

    public static char bytesToChar_LE(byte[] bytes) {
        if (bytes == null || bytes.length < 0)
            return ' ';
        ByteBuffer buffer = ByteBuffer.wrap(bytes);
        buffer.order(ByteOrder.LITTLE_ENDIAN);
        return buffer.getChar();
    }

    public static void reverse(byte[] bytes) {
        int i = 0;
        for (int j = bytes.length - 1; j > i; ++i) {
            byte tmp = bytes[j];
            bytes[j] = bytes[i];
            bytes[i] = tmp;
            --j;
        }
    }

    public static String byteToStr(byte[] buffer) {
        try {
            int length = 0;
            for (int i = 0; i < buffer.length; ++i) {
                if (buffer[i] == 0) {
                    length = i;
                    break;
                }
                length++;
            }
            return new String(buffer, 0, length, "UTF-8");
        } catch (Exception e) {
            return "";
        }
    }

    public static String byteToStrGb2312(byte[] buffer) {
        try {
            int length = 0;
            for (int i = 0; i < buffer.length; ++i) {
                if (buffer[i] == 0) {
                    length = i;
                    break;
                }
                length++;
            }
            return new String(buffer, 0, length, "GB2312");
        } catch (Exception e) {
            return "";
        }
    }
}
